package com.mengdie.shuidi.helper;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;

import com.meituan.robust.Patch;
import com.meituan.robust.PatchExecutor;
import com.meituan.robust.RobustCallBack;
import com.mengdie.shuidi.AppConfig;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.AppManager;
import com.mengdie.shuidi.manager.MDAccountMgr;
import com.mengdie.shuidi.manager.RobustVersionManager;
import com.mengdie.shuidi.model.ExceedUserEnetity;
import com.mengdie.shuidi.model.PayInfo;
import com.mengdie.shuidi.module.update.DownloadService;
import com.mengdie.shuidi.module.update.ICallbackResult;
import com.mengdie.shuidi.robust.PatchManipulateImp;
import com.mengdie.shuidi.ui.activity.BindPhoneActivity;
import com.mengdie.shuidi.ui.activity.HtmlWebActivity;
import com.mengdie.shuidi.ui.activity.LoginActivity;
import com.mengdie.shuidi.ui.activity.RegistBindPhoneActivity;
import com.mengdie.shuidi.ui.activity.WebViewActivity;
import com.mengdie.shuidi.ui.dialog.AddEtDialogFragment;
import com.mengdie.shuidi.ui.dialog.AddressDialogFragment;
import com.mengdie.shuidi.ui.dialog.CollectDialogFragment;
import com.mengdie.shuidi.ui.dialog.TerminalDialogFragment;
import com.orhanobut.logger.Logger;
import com.tencent.mm.sdk.modelbiz.JumpToBizProfile;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.List;

/**
 * 作者：HQY on 16/10/31 10:36
 * 邮箱：hqy_xz@126.com
 */

public class UIHelper {

    public static final String TERMINAL = "teminal";
    public static final String LOGIN_DIALOG = "login_dialog";
    public static final String SPLASH_DIALOG = "splsh_dialog";
    public static final String MODEL = "model";
    public static final String TYPE = "type";
    public static final String ADD_ET = "add_et";
    public static final String SELECT_ADDRESS = "select_address";
    public static final String NUMBER = "number";
    public static final String LINE_ID = "line_id";
    public static final String PACKAGE_ID = "package_id";

    public static void showTerminal(FragmentActivity activity, List<ExceedUserEnetity> exceedUserEnetityList, String type, String closeType) {
        FragmentManager fm = activity.getSupportFragmentManager();
        Fragment fragment = fm.findFragmentByTag(TERMINAL);
        if (fragment == null) {
            DialogFragment dialog = TerminalDialogFragment.newInstance(exceedUserEnetityList, type, closeType);
            dialog.show(fm, TERMINAL);
        }
    }

    public static void doPay(Context context, PayInfo payInfo) {
        Logger.d(payInfo.toString());

        IWXAPI iwxapi = WXAPIFactory.createWXAPI(context.getApplicationContext(), AppConfig.WX_APP_ID);
        PayReq req = new PayReq();
        req.appId = payInfo.appId;
        req.partnerId = payInfo.partnerId;  // 商户号
        req.prepayId = payInfo.prepayId;  // 微信返回的支付交易会话ID
        req.nonceStr = payInfo.nonceStr;
        req.timeStamp = payInfo.timeStamp;
        req.packageValue = payInfo.packageValue;
        req.sign = payInfo.sign;


        iwxapi.sendReq(req);

    }

    /**
     * 跳转到微信公众号
     *
     * @param str
     */
    public static void goWXPublic(String str) {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(AppContext.getInstance(), AppConfig.WX_APP_ID);
        JumpToBizProfile.Req req = new JumpToBizProfile.Req();
        req.toUserName = "zhimadaili"; //公众号原始ID
        req.profileType = JumpToBizProfile.JUMP_TO_NORMAL_BIZ_PROFILE;
        req.extMsg = str;
        iwxapi.sendReq(req);
    }


    public static void bindPhonePage(Context context) {
        Intent intent = new Intent(context, BindPhoneActivity.class);
        context.startActivity(intent);
    }

    public static void bindPhonePage2(Context context, String name, String username, String pass) {
        Intent intent = new Intent(context, RegistBindPhoneActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("username", username);
        intent.putExtra("pass", pass);
        context.startActivity(intent);
    }

    /**
     * 跳转到登录界面
     *
     * @param activity
     */
    public static void goLoginPage(Activity activity) {
        Intent loginIntent = new Intent(activity, LoginActivity.class);
        AppManager.getAppManager().removeActivity(activity);
        AppManager.getAppManager().finishAllActivity();
        MDAccountMgr.getInstance().clearAccountInfo();
        activity.startActivity(loginIntent);

        activity.finish();
    }

    /**
     * 跳转到 webview
     *
     * @param title
     * @param url
     */
    public static void goWebViewIntent(Context context, String title, String url) {
        Intent webview = new Intent(context, WebViewActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putString("url", url);
        webview.putExtras(bundle);
        context.startActivity(webview);
    }


    public static void openDownLoadService(Context context, String downurl,
                                           String tilte) {
        final ICallbackResult callback = new ICallbackResult() {

            @Override
            public void OnBackResult(Object s) {
            }
        };
        ServiceConnection conn = new ServiceConnection() {

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                DownloadService.DownloadBinder binder = (DownloadService.DownloadBinder) service;
                binder.addCallback(callback);
                binder.start();

            }
        };
        Intent intent = new Intent(context, DownloadService.class);
        intent.putExtra(DownloadService.BUNDLE_KEY_DOWNLOAD_URL, downurl);
        intent.putExtra(DownloadService.BUNDLE_KEY_TITLE, tilte);
        context.startService(intent);
        context.bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }


    public static void goWeb(Context context, String url) {
        Intent intent = HtmlWebActivity.newIntent(url);
        intent.setClass(AppContext.getInstance(), HtmlWebActivity.class);
        context.startActivity(intent);
    }

    /**
     * 加载补丁
     *
     * @param isChange false 表示不储存虚拟版本号
     * @param vCode    虚拟 code
     * @param vName    虚拟外部版本
     */
    public static void loadPatch(final boolean isChange, final int vCode, final String vName) {
        new PatchExecutor(AppContext.getInstance(), new PatchManipulateImp(), new RobustCallBack() {
            @Override
            public void onPatchListFetched(boolean result, boolean isNet) {
            }

            @Override
            public void onPatchFetched(boolean result, boolean isNet, Patch patch) {
            }

            @Override
            public void onPatchApplied(boolean result, Patch patch) {
                if (isChange) {
                    if (result) {
                        RobustVersionManager.getInstance().setvCode(vCode);
                        RobustVersionManager.getInstance().setvName(vName);
                        RobustVersionManager.getInstance().saveVersion();
                    } else {
                        Logger.e("false");
                    }
                } else {
                    Logger.e("没有保存版本信息");
                }

            }

            @Override
            public void logNotify(String log, String where) {
                Logger.e("logNotify" + log);
            }

            @Override
            public void exceptionNotify(Throwable throwable, String where) {

            }
        }).start();
    }

    /**
     * 分组列表
     *
     * @param activity
     * @param type
     */
    public static void showCollectDialog(FragmentActivity activity, String type) {
        FragmentManager fm = activity.getSupportFragmentManager();
        Fragment fragment = fm.findFragmentByTag(TYPE);
        if (fragment == null) {
            DialogFragment dialog = CollectDialogFragment.newInstance(type);
            dialog.show(fm, TYPE);
        }
    }

    /**
     * 添加收藏分组或修改备注
     *
     * @param activity
     * @param type
     */
    public static void showAddEtDialog(FragmentActivity activity, String type, String lineId) {
        FragmentManager fm = activity.getSupportFragmentManager();
        Fragment fragment = fm.findFragmentByTag(ADD_ET);
        if (fragment == null) {
            DialogFragment dialog = AddEtDialogFragment.newInstance(type, lineId);
            dialog.show(fm, ADD_ET);
        }
    }

    /**
     * 选择屏蔽城市
     *
     * @param activity
     */
    public static void showAddressDialog(FragmentActivity activity, String type, String num) {
        FragmentManager fm = activity.getSupportFragmentManager();
        Fragment fragment = fm.findFragmentByTag(SELECT_ADDRESS);
        if (fragment == null) {
            DialogFragment dialog = AddressDialogFragment.newInstance(type, num);
            dialog.show(fm, SELECT_ADDRESS);
        }
    }

}
